<template>
  <el-card class="content">
    <el-form inline>
      <el-form-item label="企业">
        <el-input
          placeholder="请输入企业名"
          size="mini"
          v-model="query.platformName"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="getUnitPlatformByPage"
          >查询</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addUnitPlatform"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <p class="bg-purple">企业信息列表</p>
    <el-table
      stripe
      size="small"
      class="el-table-box"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      :data="unitPlatformInfoList"
    >
      <el-table-column
        prop="platformName"
        label="企业端平台名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="platformCode"
        label="企业端路径编码"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="logo" label="logo" align="center">
        <template slot-scope="scope">
          <div @click="srcDate(scope.row)">
            <el-image
              v-if="scope.row.logo != ''"
              :src="imgUrl + scope.row.logo"
              class="picture"
              :preview-src-list="srcBigLogoList"
            ></el-image>
            <div class="imgNull" v-else-if="scope.row.logo == ''"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="background" label="背景图" align="center">
        <template slot-scope="scope">
          <div @click="srcDate(scope.row)">
            <el-image
              v-if="scope.row.background != ''"
              :src="imgUrl + scope.row.background"
              class="picture"
              :preview-src-list="srcBigBackgroundList"
            ></el-image>
            <div class="imgNull" v-else-if="scope.row.background == ''"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="wordart" label="企业名称图" align="center">
        <template slot-scope="scope">
          <div @click="srcDate(scope.row)">
            <el-image
              v-if="scope.row.wordart != ''"
              :src="imgUrl + scope.row.wordart"
              class="unitName"
              :preview-src-list="srcBigWordartList"
            ></el-image>
            <div class="imgNull" v-else-if="scope.row.wordart == ''"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateRoleInfo(scope.row)"
            >修改</el-button
          >
          <el-button type="text" size="small" @click="delUser(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 15]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 新增企业信息 -->
    <el-dialog
      title="添加企业端信息"
      :visible.sync="addDialogVisible"
      width="40%"
      style="margin-top: 0.6rem"
      @close="closeDialogVisible"
    >
      <el-form
        :model="addListForm"
        ref="addListForm"
        size="medium"
        label-position="left"
        inline
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业端平台名称" prop="unitId">
              <el-select
                v-model="addListForm.unitId"
                clearable
                placeholder="请选择企业端平台名称"
                size="mini"
              >
                <el-option
                  v-for="item in unitInfoList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.platformName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业端路径编码" prop="platformCode">
              <el-input
                v-model="addListForm.platformCode"
                placeholder="请填写企业端路径编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业logo" prop="logo">
              <el-upload
                class="avatar-uploader"
                ref="logoUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :limit="1"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <img
                  v-if="addListForm.logo"
                  :src="imgUrl + addListForm.logo"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业背景图" prop="background">
              <el-upload
                class="avatar-uploader"
                ref="backgroundUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccessBackground"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="addListForm.background"
                  :src="imgUrl + addListForm.background"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称图" prop="wordart">
              <el-upload
                class="avatar-uploader"
                ref="wordartUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccessWordart"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="addListForm.wordart"
                  :src="imgUrl + addListForm.wordart"
                  class="unitNameAvatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="buttonfrom">
          <el-button type="primary" @click="addtUnitPlatform">确 定</el-button>
          <el-button @click="closeDialogVisible">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改企业信息 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editDialogVisible"
      width="40%"
    >
      <el-form
        :model="editListForm"
        ref="editListForm"
        label-position="left"
        inline
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="unitId">
              <el-input
                v-model="editListForm.name"
                clearable
                placeholder="请选择企业端平台名称"
                size="mini"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业端路径编码" prop="platformCode">
              <el-input
                v-model="editListForm.platformCode"
                placeholder="请填写企业端路径编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业logo" prop="logo">
              <el-upload
                class="avatar-uploader"
                ref="logoUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :show-file-list="false"
                :on-success="handleEditSuccess"
                :before-upload="beforeAvatarUpload"
                accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <img
                  v-if="editListForm.logo"
                  :src="imgUrl + editListForm.logo"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业背景图" prop="background">
              <el-upload
                class="avatar-uploader"
                ref="backgroundUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :show-file-list="false"
                :on-success="handleEditSuccessBackground"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="editListForm.background"
                  :src="imgUrl + editListForm.background"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称图" prop="wordart">
              <el-upload
                class="avatar-uploader"
                ref="wordartUpload"
                :action="uploadUrl + '/group/unitPlatformImage/imageUpload'"
                :show-file-list="false"
                :on-success="handleEditSuccessWordart"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="editListForm.wordart"
                  :src="imgUrl + editListForm.wordart"
                  class="unitNameAvatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="buttonfrom">
          <el-button type="primary" @click="isEditRoleInfo">确 定</el-button>
          <el-button @click="editDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getUnitPlatformByPage,
  imageUpload,
  selectIncreasableUnitInfo,
  deleteUnitPlatform,
  uploadUrl,
  imgUrl,
} from "../../api/user";
import axios from "axios";
export default {
  name: "UnitManagement",
  data() {
    return {
      query: {
        page: 1,
        pagesize: 10,
        platformName: "",
      },
      uploadUrl,
      imgUrl,
      token: localStorage.getItem("token"),
      total: null,
      srcBigLogoList: [], // logo放大
      srcBigBackgroundList: [], // background放大
      srcBigWordartList: [], // wordart放大
      unitPlatformInfoList: [],
      addDialogVisible: false,
      addListForm: {
        unitId: null,
        platformCode: "",
        logo: "",
        background: "",
        wordart: "",
      },
      editDialogVisible: false,
      editListForm: {
        id: null,
        unitId: null,
        platformCode: "",
        logo: "",
        background: "",
        wordart: "",
        name: "",
      },
      unitInfoList: [],
      unitInfoLists: [],
      dialogWidth: null,
      // 添加角色表单验证
      rules: {
        platformName: [
          { required: true, message: "请输入角色姓名", trigger: "blur" },
        ],
        platformCode: [
          { required: true, message: "请选择角色类型", trigger: "change" },
        ],
        logoUpload: [{ required: true, message: "请上传图片" }],
        backgroundUpload: [{ required: true, message: "请上传图片" }],
        wordartUpload: [{ required: true, message: "请上传图片" }],
        unitId: [{ required: true, message: "请选择企业", trigger: "change" }],
      },
    };
  },
  created() {
    this.$common.treeVisible = false;
    this.getUnitPlatformByPage();
    // this.selectIncreasableUnitInfo();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setDialogWidth();
      })();
    };
  },
  methods: {
    // 分页查询企业端信息
    async getUnitPlatformByPage() {
      const res = await getUnitPlatformByPage({
        pageCount: this.query.page,
        pageSize: this.query.pagesize,
        platformName: this.query.platformName,
      });
      if (res.resultCode == "200") {
        this.unitPlatformInfoList = res.parameter.list;
        this.total = res.parameter.total;
      } else {
        this.$message({
          message: "暂无数据",
          offset: 400,
          duration: 1000,
        });
        this.unitPlatformInfoList = [];
        this.total = 0;
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getUnitPlatformByPage();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(val) {
      this.query.page = val;
      this.getUnitPlatformByPage();
    },
    srcDate(row) {
      this.srcBigLogoList = [];
      this.srcBigBackgroundList = [];
      this.srcBigWordartList = [];
      if (row.logo || row.background || row.wordart) {
        this.srcBigLogoList.push(imgUrl + row.logo);
        this.srcBigBackgroundList.push(imgUrl + row.background);
        this.srcBigWordartList.push(imgUrl + row.wordart);
      }
    },
    addUnitPlatform() {
      this.addDialogVisible = true;
      this.selectIncreasableUnitInfo();
    },
    // 企业列表
    async selectIncreasableUnitInfo() {
      const res = await selectIncreasableUnitInfo();
      if ((res.resultCode = 200)) {
        this.unitInfoList = res.parameter;
      } else {
        this.unitInfoList = [];
      }
    },
    // 上传logo图片成功
    async handleAvatarSuccess(res, file, fileList) {
      console.log(res.data);
      this.addListForm.logo = res.data;
    },
    // 上传logo图片前的验证
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/jpg";
      const isLt4M = file.size / 1024 / 1024 < 4;

      if (!isJPG) {
        this.$message.error("上传头像图片格式不对!");
      }
      if (!isLt4M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isJPG && isLt4M;
    },
    handleAvatarSuccessBackground(res, file) {
      this.addListForm.background = res.data;
    },
    handleAvatarSuccessWordart(res, file) {
      this.addListForm.wordart = res.data;
    },
    // 添加确定
    async addtUnitPlatform() {
      this.$refs.addListForm.validate(async (val) => {
        if (val) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.addListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/group/unitPlatform/insertUnitPlatform",
            data: formData,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.getUnitPlatformByPage();
              this.$message({
                type: "success",
                message: "新增成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "新增失败",
                offset: 400,
                duration: 1000,
              });
            }
          });
          this.addDialogVisible = false;
        } else {
          this.$message({
            type: "error",
            message: "请完善表单信息",
            offset: 400,
            duration: 500,
          });
        }
      });
    },
    //添加取消
    closeDialogVisible() {
      this.addDialogVisible = false;
      this.$refs.addListForm.resetFields();
    },
    // 上传修改后的logo
    handleEditSuccess(res) {
      this.editListForm.logo = res.data;
    },
    // 上传修改后的background
    handleEditSuccessBackground(res) {
      this.editListForm.background = res.data;
    },
    // 上传修改后的wordart
    handleEditSuccessWordart(res) {
      this.editListForm.wordart = res.data;
    },
    // 将原数据回显
    updateRoleInfo(row) {
      console.log(row);
      this.editListForm.id = row.id;
      this.editListForm.name = row.platformName;
      this.editListForm.unitId = row.unitId;
      this.editListForm.platformCode = row.platformCode;
      this.editListForm.logo = row.logo;
      this.editListForm.background = row.background;
      this.editListForm.wordart = row.wordart;
      this.editDialogVisible = true;
    },
    // 确定修改企业信息
    isEditRoleInfo() {
      this.$refs.editListForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.editListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/group/unitPlatform/updateUnitPlatform",
            data: formData,
          }).then((res) => {
            console.log(res);
            if (res.data.resultCode == 200) {
              this.getUnitPlatformByPage();
              this.$message({
                type: "success",
                message: "修改成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message({
                type: "error",
                message: "修改失败",
                offset: 400,
                duration: 1000,
              });
            }
            this.editDialogVisible = false;
          });
        } else {
          this.$message({
            type: "error",
            message: "请完成表单",
            offset: 400,
            duration: 1000,
          });
        }
      });
    },
    //删除企业信息
    async delUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将强制永久删除该数据, 是否继续?",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message({
          message: "已取消删除",
          type: "info",
          offset: 450,
          duration: 1000,
        });
      }
      await deleteUnitPlatform({
        id: Number(id),
      }).then((res) => {
        if (res.resultCode == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
            offset: 450,
            duration: 1000,
          });
          this.getUnitPlatformByPage();
        } else if (res.resultCode == 410) {
          this.$message({
            message: "无权限删除",
            type: "warning",
            offset: 450,
            duration: 1000,
          });
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
            offset: 450,
            duration: 1000,
          });
        }
      });
    },
    setDialogWidth() {
      var val = document.body.clientWidth;
      const def = 750; // 默认宽度
      if (val < def) {
        this.dialogWidth = "100%";
      } else {
        this.dialogWidth = def + "px";
      }
    },
  },
};
</script>

<style scoped>
.content {
  margin: 0 0.08rem;
  font-size: 0.07rem;
  height: 90vh;
}

.bg-purple {
  background: #d3dce6;
  height: 0.15rem;
  font-size: 0.07rem;
  line-height: 0.15rem;
  padding-left: 0.05rem;
}
.el-button {
  font-size: 0.07rem;
}
.el-table-box {
  margin-bottom: 0.1rem;
  display: block;
  height: 65vh;
  overflow: auto;
}
.el-table::before {
  z-index: inherit;
}
table {
  text-align: center;
}
.buttonfrom {
  margin-left: 1.5rem;
}
.avatar-uploader {
  width: 1rem;
  height: 1rem;
  border: 1px dashed #d9d9d9;
  border-radius: 0.03rem;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 0.03rem;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 0.14rem;
  color: #8c939d;
  width: 1rem;
  height: 1rem;
  line-height: 1rem;
  text-align: center;
}
.avatar {
  width: 1rem;
  height: 1rem;
  display: block;
  border-radius: 0.03rem;
  box-sizing: border-box;
}
.unitNameAvatar {
  width: 1rem;
  height: 1rem;
  display: block;
  border-radius: 0.03rem;
  background-color: #dddddd;
  padding: 0.05rem;
  box-sizing: border-box;
}
.imgNull {
  width: 0.5rem;
  height: 0.5rem;
}
.picture {
  width: 0.5rem;
  height: 0.5rem;
  padding: 0.05rem;
  box-sizing: border-box;
}
.unitName {
  width: 0.5rem;
  height: 0.5rem;
  background-color: #d3d3d3;
  padding: 0.05rem;
  box-sizing: border-box;
}
</style>

  


